package com.jk.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jk.common.Commonfig;
import com.jk.model.*;
import com.jk.service.ZSLService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("zsl")
public class ZSLController<DataGridResult> {

    @Reference(check = false)
    private ZSLService zslService;

    /**
     * 注入mongodb
     */
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 加入购物车  mongodb
     * @param productId
     * @param request
     * @return
     */
    @RequestMapping("saveShop")
    @ResponseBody
    public Map saveShop(Integer productId,HttpServletRequest request){
        HashMap<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());
        if (attribute == null){
            result.put("code",1);
            result.put("msg","请登录");
            return null;
        }
        ShopBean shopBean = new ShopBean();
        shopBean.setCreateTime(new Date().toString());
        shopBean.setProductId(productId);
        shopBean.setUserId(attribute.getId());
        result.put("code",0);
        result.put("msg","加入成功");
        mongoTemplate.save(shopBean);
        return result;
    }

    /**
     * 模拟购物车数据
     * @param request
     * @return
     */
    @RequestMapping("shopping")
    @ResponseBody
    public Map shopping(HttpServletRequest request){
        HashMap<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession();
        UserBean user = (UserBean) session.getAttribute(session.getId());
        /*if (user == null){
            result.put("code",1);
            result.put("msg","请登录");
            return result;
        }*/
        Integer id = user.getId();
        //String id="1";
        Query query = new Query();

        query.addCriteria(Criteria.where("userId").is(id));
        List<ShopBean> shopBeans = mongoTemplate.find(query, ShopBean.class);
        ArrayList<ProductBean> list = new ArrayList<>();
        for (ShopBean shopBean : shopBeans) {
            ProductBean productBean=zslService.queryProductByProductId(shopBean.getProductId());
            list.add(productBean);
        }
        result.put("rows",list);
        return result;
    }

    /**
     * 根据订单查询订单中的商品
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("chajiaoyi")
    public List<OrderBean> chajiaoyi(HttpServletRequest request){
        HttpSession session = request.getSession();
        UserBean user = (UserBean) session.getAttribute(session.getId());
        String zhifuzhuangtai = Commonfig.ZHIFUZHUANGTAI+user.getId();
        String o = redisTemplate.opsForValue().get(zhifuzhuangtai).toString();
        //String s = JSON.toJSONString(o);
        List<OrderBean> orderBeans = JSONArray.parseArray(o, OrderBean.class);
        List<OrderBean> row=new ArrayList<>();
        for (OrderBean orderBean : orderBeans) {
            OrderBean order = zslService.chajiaoyi(orderBean.getProductId());
            order.setOrderPrice(orderBean.getOrderPrice());
            order.setProductCount(orderBean.getProductCount());
            order.setOrderNo(orderBean.getOrderNo());
            row.add(order);
        }
        /*for (int i = 0; i < orderBeans.size(); i++) {
            OrderBean order = zslService.chajiaoyi(orderBeans.get(i).getProductId());
            order.setOrderPrice(orderBeans.get(i).getOrderPrice());
            order.setProductCount(orderBeans.get(i).getProductCount());
            order.setOrderNo(orderBeans.get(i).getOrderNo());
            row.add(order);
            //orderBeans.get(i).getProductId()
        }*/
        return row;
    }

    /**
     * 查询收货地址
     * @param request
     * @return
     */
    @RequestMapping("chaaddress")
    @ResponseBody
    public Map chaaddress(HttpServletRequest request){
        /*HttpSession session = request.getSession();
        UserBean attribute = (UserBean) session.getAttribute(session.getId());*/
        List<AcceptsiteBean> row = zslService.chaAddress(1);
        HashMap<String, Object> result = new HashMap<>();
        result.put("rows",row);
        return result;
    }
    /**
     * 跳转支付页面
     * @param request
     * @return
     */
    @RequestMapping("zhifuyemian")
    public ModelAndView zhifuyemian(HttpServletRequest request){
        String zhifuzhuangtai = Commonfig.ZHIFUZHUANGTAI+1;
        String o = redisTemplate.opsForValue().get(zhifuzhuangtai).toString();
        List<OrderBean> orderBeans = JSON.parseArray(o, OrderBean.class);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("shoppIng/cha");
        for (OrderBean orderBean : orderBeans) {
            modelAndView.addObject("ordernumber",orderBean);
        }
        return modelAndView;
    }

    /**
     * 生成订单
     * @param productid
     * @param count
     * @param productprice
     * @param request
     * @return
     */
    @RequestMapping("saveOrder")
    @ResponseBody
    public Boolean saveOrder(Integer[] productid,Integer[] count,double[] productprice,HttpServletRequest request){
        try {
            HttpSession session = request.getSession();
            UserBean user = (UserBean) session.getAttribute(session.getId());

            LinkedList<OrderBean> objects1 = new LinkedList<>();
            //ArrayList<OrderBean> objects = new ArrayList<>();
            for (int i = 0; i < productid.length; i++) {
                OrderBean orderBean = new OrderBean();
                //时间戳
                orderBean.setOrderNo(String.valueOf(System.currentTimeMillis()));
                //用户id
                orderBean.setUserId(user.getId());
                //商品id
                orderBean.setProductId(productid[i]);
                //商品数量
                orderBean.setProductCount(count[i]);
                //商品总价
                orderBean.setOrderPrice(productprice[i]);
                //付款状态 默认为1
                orderBean.setOrderStatus(1);
                //创建时间
                Date date = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateString = formatter.format(date);
                orderBean.setOrderCreateTime(dateString);
                objects1.add(orderBean);
            }
            String zhifuzhuangtai = Commonfig.ZHIFUZHUANGTAI+user.getId();
            //String s = JSON.toJSONString(objects);
            if (!redisTemplate.hasKey(zhifuzhuangtai)){
                String jsonString = JSON.toJSONString(objects1);
                redisTemplate.opsForValue().set(zhifuzhuangtai, jsonString, 30, TimeUnit.MINUTES);
                //redisTemplate.opsForValue().set(zhifuzhuangtai,objects1,30, TimeUnit.MINUTES);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 查询树
     * @return
     */
    @RequestMapping("findManageTree")
    @ResponseBody
    public List<ManageBean> findManageTree(){
        List<ManageBean> manageTree = zslService.findManageTree();
        return manageTree;
    }

    /**
     * 查询用户信息
     * @param page
     * @param rows
     * @param userBean
     * @return
     */
    @RequestMapping("findUserList")
    @ResponseBody
    public Map findUserList(Integer page, Integer rows, UserBean userBean){
        return zslService.findUserList(page,rows,userBean);
    }

    /**
     * 删除用户信息
     * @param ids
     * @return
     */
    @RequestMapping("delUserById")
    @ResponseBody
    public Boolean delUserById(Integer[] ids){
        try {
            zslService.delUserById(ids);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 通过用户id查询所拥有的店铺
     * @param page
     * @param rows
     * @param userBean
     * @return
     */
    @RequestMapping("findUserShopList")
    @ResponseBody
    public Map findUserShopList(Integer page, Integer rows, UserBean userBean){
        return zslService.findUserShopList(page,rows,userBean);
    }

    @RequestMapping("findShopUserList")
    @ResponseBody
    public Map findShopUserList(Integer page, Integer rows, UserBean userBean){
        Map shopUserList = zslService.findShopUserList(page, rows, userBean);
        return shopUserList;
    }

    /**
     * 商家所拥有的商品
     * @param page
     * @param rows
     * @param productBean
     * @param id
     * @return
     */
    @RequestMapping("shopTable")
    @ResponseBody
    public Map shopTable(Integer page, Integer rows, ProductBean productBean, Integer id){
        return zslService.shopTable(page,rows,productBean,id);
    }

    /**
     * 查询所有订单信息
     * @param page
     * @param rows
     * @param orderBean
     * @return
     */
    @RequestMapping("findOrderList")
    @ResponseBody
    public Map findOrderList(Integer page, Integer rows, OrderBean orderBean){
        return zslService.findOrderList(page,rows,orderBean);
    }

    /**
     * 根据店铺商品查询订单
     * @param page
     * @param rows
     * @param orderBean
     * @param id
     * @return
     */
    @RequestMapping("orderTable")
    @ResponseBody
    public Map orderTable(Integer page, Integer rows, OrderBean orderBean,Integer id){
        return zslService.orderTable(page, rows, orderBean, id);
    }

}
